﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace FrameworkDesign
{
    public class Singleton<T> where T : Singleton<T>
    {
        private static T mInstance;

        public static T Instance
        {
            get
            {
                if(mInstance == null)
                {
                    var type = typeof(T);
                    // ctors变量 存储的是一个构造函数的数组
                    var ctors = type.GetConstructors(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                    // 获取第一个无参构造数组
                    var ctor = System.Array.Find(ctors, c => c.GetParameters().Length == 0);

                    if(ctor == null)
                    {
                        throw new System.Exception("Non Public Constructor Not Fount in " + type.Name);
                    }

                    mInstance = ctor.Invoke(null) as T;

                    // 泛型单例，涉及到一些C#反射知识
                }
                return mInstance;
            }
        }
    }

}
